<template>
  <div class="app-container">
    <CommonContainer title="用户信息">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
        <el-row>
          <el-col :span="8">
            <el-form-item label="用户姓名" prop="nickName">
              <el-input style="width: 80%" v-model="form.nickName" placeholder="请输入用户姓名" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="归属组织" prop="deptId">
              <treeselect style="width: 80%; height: 25px" v-model="form.deptId" :options="deptOptions"
                          :defaultExpandLevel="10" :show-count="true" placeholder="请选择归属组织"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input style="width: 80%" v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱" prop="email">
              <el-input style="width: 80%" v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户账号" prop="userName">
              <el-input style="width: 80%" v-model="form.userName" placeholder="请输入用户账号" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.userId == undefined">
            <el-form-item label="用户密码" prop="password">
              <el-input class="password-input" style="width: 80%" v-model="form.password" placeholder="请输入用户密码"
                        type="text"
                        maxlength="20" onkeyup="value=value.replace(/[\u4E00-\u9FA5]/g,'')">
                <i slot="suffix" class="el-icon-view" @click="hiddenPwd"></i>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="用户性别">
              <el-select style="width: 80%" v-model="form.sex" placeholder="请选择性别">
                <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="角色" prop="roleIds">
              <el-select style="width: 80%" v-model="form.roleIds" multiple placeholder="请选择角色" filterable>
                <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId"
                           :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="岗位" prop="postIds">
              <el-select style="width: 80%" v-model="form.postIds" multiple placeholder="请选择岗位" filterable>
                <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
                           :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="NC员工id" prop="ncId">
              <el-input style="width: 80%" v-model="form.ncId" placeholder="请输入NC员工id" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="NC员工编码" prop="ncCode">
              <el-input style="width: 80%" v-model="form.ncCode" placeholder="请输入NC员工编码" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="OA员工编码" prop="oaCode">
              <el-input style="width: 80%" v-model="form.oaCode" placeholder="请输入OA员工编码" maxlength="50"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="nc供应商id" prop="ncSupplierId">
              <el-input style="width: 80%" v-model="form.ncSupplierId" placeholder="请输入nc供应商id" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="nc供应商code" prop="ncSupplierCode">
              <el-input style="width: 80%" v-model="form.ncSupplierCode" placeholder="请输入nc供应商code"
                        maxlength="50"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="用户状态">
              <el-radio-group style="width: 80%" v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{
                    dict.label
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务类型" required>
              <el-radio-group style="width: 80%" v-model="form.businessType">
                <el-radio v-for="dict in dict.type.user_business_type" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="岗位状态" required>
              <el-radio-group style="width: 80%" v-model="form.workingCondition">
                <el-radio label="1">在岗</el-radio>
                <el-radio label="2">离岗</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <div style="padding-bottom: 18px">账户信息</div>
            <el-table border :data="form.accounts" :header-cell-class-name="headerClass" style="width: 100%">
              <el-table-column type="index" key="index" width="50" align="center" label="序号"/>

              <el-table-column prop="accountName" key="accountName" align="center" min-width="170" label="开户名称">
                <template #default="{ row, $index }">
                  <el-form-item label-width="0" :prop="`accounts.${$index}.accountName`" :rules="{
                      required: true,
                      message: '请输入开户名称',
                      trigger: 'blur',
                    }">
                    <el-input maxlength="50" v-model="row.accountName" clearable placeholder="请输入开户名称"/>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="bankName" key="bankName" align="center" min-width="170" label="开户银行">
                <template #default="{ row, $index }">
                  <el-form-item label-width="0" :prop="`accounts.${$index}.bankName`" :rules="{
                      required: true,
                      message: '请选择开户银行',
                      trigger: 'change',
                    }">
                    <el-input @focus="select_dialog(row, $index)" v-model="row.bankName" ref="selectDialogInput"
                              clearable @clear="clear(row)" placeholder="请选择开户银行"/>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="accountNumber" key="accountNumber" align="center" min-width="170" label="银行账户">
                <template #default="{ row ,$index}">
                  <el-form-item label-width="0" :prop="`accounts.${$index}.accountNumber`" :rules="{
                      required: true,
                      message: '请输入银行账户',
                      trigger: 'blur',
                    }">
                    <el-input maxlength="30" @input="
                        (value) =>
                          (row.accountNumber = value.replace(/[^\d]/g, ''))
                      "
                              v-model="row.accountNumber" clearable placeholder="请输入银行账户"/>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="accountStatus" key="accountStatus" align="center" width="125"
                               label="是否为生效账号">
                <template #default="{ row }">
                  <el-switch active-value="0" inactive-value="1" v-model="row.accountStatus">
                  </el-switch>
                </template>
              </el-table-column>

              <el-table-column label="操作" width="80" align="center" class-name="small-padding fixed-width">
                <template #default="{ row, $index }">
                  <e-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(row, $index)">删除
                  </e-button>
                </template>
              </el-table-column>

              <template v-slot:append>
                <div class="flex-xy-center" style="height: 40px">
                  <e-button type="text" icon="eel-icon-plus" @click="addAccount">新增
                  </e-button>
                </div>
              </template>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
    </CommonContainer>
    <div class="card-wrap flex justify-end card-padding">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">保 存</el-button>
    </div>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  addUser,
  deptTreeSelect,
  updateUser,
  getUser,
  getUserUpdate,
  userBankAccount
} from "@/api/system/user";

export default {
  name: "UserAdd",
  dicts: ["sys_normal_disable", "sys_user_sex", "user_business_type"],
  components: {Treeselect},
  props: {},
  data() {
    // 密码校验 长度不能小于8位且不能大于20位字符,必须包含大写字母、小写字母、数字和特殊符号
    const ISPWD = /^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*,\._\+(){}])[0-9a-zA-Z!@#$%^&*,\\._\+(){}]{8,20}$/;
    // 密码校验
    const validatePassword = (rule, value, callback) => {
      if (!ISPWD.test(this.form.password)) {
        callback(
            new Error("用户密码必须包含大写字母、小写字母、数字和特殊符号")
        );
      } else {
        callback();
      }
    };
    return {
      // 组织树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 组织名称
      deptName: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      form: {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
        businessType: "1",
        workingCondition: "1",
        ncName: null, //ncName
        ncId: null, //ncId
        ncCode: null, //nc编码
        oaCode: null, //oa编码
        ncSupplierId: null, //
        ncSupplierCode: null, //
        accounts: [],
      },
      // 表单校验
      rules: {
        userName: [
          {required: true, message: "用户账号不能为空", trigger: "blur"},
          {
            min: 2,
            max: 20,
            message: "用户账号长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        nickName: [
          {required: true, message: "用户姓名不能为空", trigger: "blur"},
        ],
        deptId: [
          {
            required: true,
            message: "请选择归属组织",
            trigger: ["blur", "change"],
          },
        ],

        password: [
          {required: true, message: "用户密码不能为空", trigger: "blur"},
          {
            min: 8,
            max: 20,
            message: "用户密码长度必须介于 8 和 20 之间",
            trigger: "blur",
          },
          {required: true, validator: validatePassword, trigger: "blur"},
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          {
            required: true,
            message: "请输入手机号码",
            trigger: ["blur"],
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        postIds: [
          {
            required: true,
            message: "请选择岗位",
            trigger: ["blur", "change"],
          },
        ],
        roleIds: [
          {
            required: true,
            message: "请选择角色",
            trigger: ["blur", "change"],
          },
        ],
      },
      showPwd: false,

      //账户信息 * 标识
      headerList: ["accountName", "bankName", "accountNumber"],
    };
  },
  computed: {},
  watch: {
    // 根据名称筛选组织树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    headerClass({row, column, rowIndex, columnIndex}) {
      for (let i = 0; i < row.length; i++) {
        if (this.headerList.includes(row[i].property) && i == columnIndex) {
          return "header-class";
        }
      }
    },

    async handleBankList() {
      this.$set(this.form, 'accounts', [])
      try {
        let res = await userBankAccount({userId: this.$route.query.userId})
        this.$set(this.form, 'accounts', res.data || [])
      } catch (e) {
        console.log(e)
      }
    },

    //新增
    addAccount() {
      this.form.accounts.push({
        bankName: null,
        bankCode: null,
        accountName: null,
        accountNumber: null,
        accountStatus: "0",
        id:null,
        userId:this.$route.query.userId || null
      });
      this.$forceUpdate();
    },
    //删除
    handleDelete(row, index) {
      this.form.accounts.splice(index, 1);
    },

    //开户银行事件
    //开户银行事件
    select_dialog(row, index) {
      this.$refs.selectDialogInput.blur();
      const SelectDialog =
          require('../../../components/A/A-form/template/index').default;

      SelectDialog({type: 'bank'})
          .then(({data, type}) => {
            const exists = this.form.accounts.some((item, ind) => item.bankCode === data.bankCode && index !== ind);
            if (exists) {
              this.$message({
                type: 'warning',
                message: '开户银行已存在'
              })
              row.bankName = '';
              row.bankCode = '';
            } else {
              row.bankName = data.bankName;
              row.bankCode = data.bankCode;
            }
          })
          .catch(err => {
          });
    },

    clear(row) {
      row.bankName = undefined;
      row.bankCode = undefined;
    },

    //获取默认信息
    getInitInfo() {
      getUser().then((response) => {
        this.postOptions = response.data.posts;
        this.roleOptions = response.data.roles;
      });
    },
    getUserInfo() {
      getUserUpdate(this.form.userId).then((response) => {
        this.form = response.data.user;
        this.postOptions = response.data.posts;
        this.roleOptions = response.data.roles;
        this.$set(this.form, "postIds", response.data.postIds);
        this.$set(this.form, "roleIds", response.data.roleIds);
        this.handleBankList()
      });
    },

    /** 查询组织下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.cancel();
            });
          } else {
            addUser(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.cancel();
            });
          }
        }
      });
    },
    hiddenPwd() {
      this.showPwd = !this.showPwd; // 默认为false
      if (this.showPwd) {
        document.getElementsByClassName(
            "password-input"
        )[0].style.webkitTextSecurity = "none";
      } else {
        document.getElementsByClassName(
            "password-input"
        )[0].style.webkitTextSecurity = "disc";
      }
    },
    // 取消按钮
    cancel() {
      this.$router.back();
      this.$store.dispatch("tagsView/delView", this.$route);
    },
  },
  created() {
    this.getDeptTree();
  },
  mounted() {
    if (this.$route.query.userId) {
      this.form.userId = this.$route.query.userId;
      this.getUserInfo();
    } else {
      this.getConfigKey("sys.user.initPassword").then((response) => {
        this.form.password = response.msg;
        this.getInitInfo();
      });
    }
  },
};
</script>

<style lang="scss" scoped>
::v-deep
.el-form
.el-form-item__content:has(.el-radio-group, .el-date-editor, .el-input, .el-checkbox
    .vue-treeselect) {
  line-height: 32px;
  height: 32px;
}

.password-input {
  position: relative;
  font-size: 14px;

  /* 调整字体大小以适配隐藏文本 */
  color: transparent; /* 将文本颜色设为透明 */
  letter-spacing: 0.25em;
  /* 调整字符间距以隐藏文本 */
  -webkit-text-security: disc;
  /* 将输入内容显示为圆点，适用于部分浏览器 */
}

::v-deep .el-input__suffix {
  right: 7px;
  -webkit-text-security: none !important;
}

::v-deep .header-class {
  .cell::before {
    content: "*";
    color: red;
    padding-right: 2px;
    font-size: 14px;
  }
}
</style>
